package com.tianheng.wanzhou.datacollecting.util;

import java.math.BigInteger;
import java.text.DecimalFormat;

public class TqlHexchange {
    //转int
    public static Integer zcInt(String hex) {
        return Integer.valueOf(hex, 16);
    }
    //转int（4位反转）
    public static Integer fz4Int(String hex) {
        String low = hex.substring(0, 2);
        String high = hex.substring(2);
        String newHex = high + low;
        return zcInt(newHex);
    }
    //转int（8位反转）
    public static Integer fz8Int(String hex) {
        String low = hex.substring(0, 4);
        String high = hex.substring(4);
        String newHex = high + low;
        return zcInt(newHex);
    }
    //转float-IEEE(8位反转)
    public static Float fz8Float(String strHex) {
        String low = strHex.substring(0, 4);
        String high = strHex.substring(4);
        String hex = high + low;
        BigInteger b = new BigInteger(hex, 16);
        Float f = Float.intBitsToFloat(b.intValue());
        DecimalFormat df = new DecimalFormat("0.0");
        df.format(f);
        return f;
    }
    //转float-IEEE
    public static Float zcFloat(String strHex){
        BigInteger b = new BigInteger(strHex, 16);
        Float f = Float.intBitsToFloat(b.intValue());
        DecimalFormat df = new DecimalFormat("0.00");
        df.format(f);
        return f;
    }
    //double-IEEE(8反转)
    public static Double fz8Double(String strHex){
        Double b = Double.parseDouble(String.valueOf(fz8Float(strHex)));
        return  b;
    }
    //转double-IEEE
    public static Double zcDouble(String strHex){
        Double b = Double.parseDouble(String.valueOf(zcFloat(strHex)));
        return  b;
    }
    //转String
    public static String zcString(String strHex){
        return zcInt(strHex).toString();
    }
    //转String(8反转)
    public static String fz8String(String strHex){
        String low = strHex.substring(0, 4);
        String high = strHex.substring(4);
        String newHex = high + low;
        return zcInt(newHex).toString();
    }
    //转String(4反转)
    public static String fz4String(String strHex){
        String low = strHex.substring(0, 2);
        String high = strHex.substring(2);
        String newHex = high + low;
        return zcInt(newHex).toString();
    }
    //转2进制字符串
    public static String hexString2binaryString(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0)
            return null;
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++) {
            tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }

}
